import React, { Component, createRef } from 'react'
import { Toast } from 'antd-mobile'
import { getCityList, getHotCityList } from '../../api/area'
import { getPostionCity } from '../../utils/getCity'
import { List, AutoSizer } from 'react-virtualized'
import NavHeader from '../../components/NavHeader'
import './index.scss'
// 标题的高度
const TITLE_HEIGHT = 36
// 城市名称的高度
const NAME_HEIGHT = 50

const HOUSE_CITY = ['北京', '上海', '深圳', '广州']

export default class CityList extends Component {
  state = {
    cityList: {},
    cityKey: [],
    activeIndex: 0,
  }

  listRef = createRef()

  async componentDidMount() {
    await this.loadCityList()
    this.listRef.current.measureAllRows()
  }
  // 处理城市列表数据
  formateCityList(list) {
    const cityList = {}
    list.forEach((item) => {
      const first = item.short.substr(0, 1)
      if (cityList[first]) {
        cityList[first].push(item)
      } else {
        cityList[first] = [item]
      }
    })
    return {
      cityList,
      cityKey: Object.keys(cityList).sort(),
    }
  }
  // 获取城市列表数据
  async loadCityList() {
    const { data: res } = await getCityList()
    const { cityList, cityKey } = this.formateCityList(res.body)
    // 获取热门城市数据
    const { data: hotRes } = await getHotCityList()
    cityKey.unshift('hot')
    cityList.hot = hotRes.body
    const cityRes = await getPostionCity()
    cityList['#'] = [cityRes]
    cityKey.unshift('#')
    this.setState({
      cityList,
      cityKey,
    })
  }
  // 渲染城市列表每一项
  rowRenderer = ({ key, index, style }) => {
    const { cityKey, cityList } = this.state
    const cityListKey = cityKey[index]
    const itemCityArr = cityList[cityListKey]
    return (
      <div key={key} style={style} className="city">
        <div className="title">{this.formateTitle(cityListKey)}</div>

        {itemCityArr.map((item) => {
          return (
            <div
              onClick={() => this.cityNameClick(item)}
              className="name"
              key={item.value}
            >
              {item.label}
            </div>
          )
        })}
      </div>
    )
  }
  //切换城市选择的方法
  cityNameClick = (item) => {
    const index = HOUSE_CITY.indexOf(item.label)
    if (index === -1) return Toast.info(item.label + '暂无房源', 2, null, false)
    this.props.history.go(-1)
    localStorage.setItem('HKZF_CITY', JSON.stringify(item))
  }
  // 格式化标题
  formateTitle(title) {
    if (title === '#') return '当前城市'
    if (title === 'hot') return '热门城市'
    return title.toUpperCase()
  }
  // 计算每一项的高度
  rowHeight = ({ index }) => {
    const { cityKey, cityList } = this.state
    const cityListKey = cityKey[index]
    return TITLE_HEIGHT + NAME_HEIGHT * cityList[cityListKey].length
  }
  rederRightIndex = () => {
    const { cityKey, activeIndex } = this.state
    return cityKey.map((item, i) => (
      <li
        key={item}
        className="city-index-item"
        onClick={() => this.onClickCityItem(i)}
      >
        {/* className="index-active" */}
        <span className={activeIndex === i ? 'index-active' : ''}>
          {item === 'hot' ? '热' : item.toUpperCase()}
        </span>
      </li>
    ))
  }
  //列表滑动的时候会触发并且能够拿到当前行的索引
  onRowsRendered = ({ startIndex }) => {
    const { activeIndex } = this.state
    if (activeIndex === startIndex) return
    this.setState({
      activeIndex: startIndex,
    })
  }
  // 点击右侧索引
  onClickCityItem(i) {
    const list = this.listRef.current
    list.scrollToRow(i)
  }
  render() {
    return (
      <div className="city-container">
        {/* 头部 */}
        <NavHeader>城市列表</NavHeader>
        {/* 列表 */}
        <AutoSizer>
          {({ width, height }) => {
            return (
              <List
                scrollToAlignment="start"
                ref={this.listRef}
                width={width}
                height={height}
                rowCount={this.state.cityKey.length}
                rowHeight={this.rowHeight}
                rowRenderer={this.rowRenderer}
                onRowsRendered={this.onRowsRendered}
              />
            )
          }}
        </AutoSizer>
        {/* 城市列表右侧索引 */}
        <ul className="city-index">{this.rederRightIndex()}</ul>
      </div>
    )
  }
}
